// pages/volunteer/acceptcall.js
import requestUtil from "../../../api/request"
import API from "../../../api/http.api"

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tips:'等待小程序加载中'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log("onLoad------------------------------------acceptcall")
    console.log(options)
    this.setData({
      tips:'等待小程序加载中'
    })
    this.callId = options.callId
    this.roomID = options.roomID
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("onShow------------------------------------acceptcall")
    var that = this
    // 等待小程序初始化完成
    this.dataInterval = setInterval(() => {
      if (app.globalData.openId != null) {
        this.setData({
          tips:'努力连接中'
        })
        clearInterval(that.dataInterval)
        console.log("小程序初始化完毕 openId ：" + app.globalData.openId)

        that.checkDeviceAuthorize().then((result) => {
          console.log('授权成功', result)
          requestUtil.post(API.HANDLE_VIDEO_CALL, {
            "callId": that.callId
          }).then((res) => {
            console.log(res)
            app.globalData.userSig = res.data.userSig
            console.log(app.globalData.userSig)
            const url = `../../room/room?userID=${app.globalData.openId}&callId=${that.callId}&roomID=${that.roomID}&cloudenv=PRO&frontCamera=front`
            wx.navigateTo({ url: url })
          }).catch((err) => {
            console.log(err)
            wx.showToast({
              title: '抱歉，已经有小伙伴赶在您前面了',
              icon: 'none',
              duration: 3000
            })
            setTimeout(() => {
              wx.redirectTo({
                url: "/pages/index/index?reSub=true"
              })
            }, 2500);
          })
        }).catch((error) => {
          console.log('没有授权', error)
          wx.showToast({
            title: '抱歉，您没有打开麦克风或视频权限',
            icon: 'none',
            duration: 3000
          })
          setTimeout(() => {
            wx.redirectTo({
              url: "/pages/index/index?reSub=true"
            })
          }, 2500);
        })
      }
    }, 200);
  },

  checkDeviceAuthorize: function() {
    this.hasOpenDeviceAuthorizeModal = false
    return new Promise((resolve, reject) => {
      if (!wx.getSetting || !wx.getSetting()) {
        // 微信测试版 获取授权API异常，目前只能即使没授权也可以通过 
        resolve()
      }
      wx.getSetting().then((result) => {
        console.log('getSetting', result)
        this.authorizeMic = result.authSetting['scope.record']
        this.authorizeCamera = result.authSetting['scope.camera']
        if (result.authSetting['scope.camera'] && result.authSetting['scope.record']) {
          // 授权成功 
          resolve()
        } else {
          // 没有授权，弹出授权窗口 
          // 注意： wx.authorize 只有首次调用会弹框，之后调用只返回结果，如果没有授权需要自行弹框提示处理 
          console.log('getSetting 没有授权，弹出授权窗口', result)
          wx.authorize({
            scope: 'scope.record',
          }).then((res) => {
            console.log('authorize mic', res)
            this.authorizeMic = true
            if (this.authorizeCamera) {
              resolve()
            }
          }).catch((error) => {
            console.log('authorize mic error', error)
            this.authorizeMic = false
          })
          wx.authorize({
            scope: 'scope.camera',
          }).then((res) => {
            console.log('authorize camera', res)
            this.authorizeCamera = true
            if (this.authorizeMic) {
              resolve()
            } else {
              this.openConfirm()
              reject(new Error('authorize fail'))
            }
          }).catch((error) => {
            console.log('authorize camera error', error)
            this.authorizeCamera = false
            this.openConfirm()
            reject(new Error('authorize fail'))
          })
        }
      })
    })
  },

  openConfirm: function() {
    if (this.hasOpenDeviceAuthorizeModal) {
      return
    }
    this.hasOpenDeviceAuthorizeModal = true
    return wx.showModal({
      content: '您没有打开麦克风和摄像头的权限，是否去设置打开？',
      confirmText: '确认',
      cancelText: '取消',
      success: (res) => {
        this.hasOpenDeviceAuthorizeModal = false
        console.log(res)
        // 点击“确认”时打开设置页面 
        if (res.confirm) {
          console.log('用户点击确认')
          wx.openSetting({
            success: (res) => {},
          })
        } else {
          console.log('用户点击取消')
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})